package com.seckill.user.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seckill.user.dto.UserLogin;
import com.seckill.user.pojo.User;
import com.seckill.user.service.UserService;
import com.seckill.util.JwtTokenUtil;
import com.seckill.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 用户表 控制器</p>
 *
 * @author 作者
 * @since 2022-03-14
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /***
     * 用户登录
     */
    @PostMapping(value = "/login")
    public Result login(@Valid @RequestBody UserLogin userLogin) throws Exception {
        //1.根据用户名查询用户信息
        User user = userService.getById(userLogin.getUsername());
        //2.用户不存在
        if(user==null){
            return Result.error("账号不存在！");
        }
        //3.密码错误
        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(userLogin.getPassword().getBytes()))){
            return Result.error("密码错误！");
        }
        //4.登录成功
        Map<String,Object> payload = new HashMap<String,Object>();
        payload.put("key","seckill");
        payload.put("username",user.getUsername());
        payload.put("name",user.getName());
        payload.put("phone",user.getPhone());
        String token = JwtTokenUtil.generateTokenUser(UUID.randomUUID().toString(), payload, 800000000L);
        return Result.ok(token);
    }

    /***
     * user分页条件搜索实现
     * @param user
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/search/{page}/{size}" )
    public Result<Page<User>> findPage(@RequestBody(required = false)  User user, @PathVariable int page, @PathVariable  int size) throws InterruptedException {
        //调用ParaService实现分页条件查询Para
        Page<User> pageInfo = userService.findPage(user, page, size);
        return Result.ok(pageInfo);
    }

    @GetMapping(value = "/all" )
    public Result all(HttpServletResponse response) throws InterruptedException {
//        if(Math.random()>0.5){
//            throw new RuntimeException("出现了异常");
//        }
        response.setHeader("Cache-Control","max-age=60");
        //调用ParaService实现分页条件查询Para
        List<User> list = userService.list();
        return Result.ok(list);
    }

}

